package com.ssy.lingxi.logistics.serviceimpl;

import cn.hutool.core.util.StrUtil;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.logistics.entity.ReceiverAddress;
import com.ssy.lingxi.logistics.model.enums.CommonBooleanEnum;
import com.ssy.lingxi.logistics.model.enums.ReceiverAddressCreateTypeEnum;
import com.ssy.lingxi.logistics.model.request.BaseReceiverAddressRequest;
import com.ssy.lingxi.logistics.model.request.ReceiverAddressAgentAddRequest;
import com.ssy.lingxi.logistics.model.response.ReceiverAddressResponse;
import com.ssy.lingxi.logistics.repository.ReceiverAddressRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收货地址服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2020/7/13
 */
@Service
public class BaseReceiverAddressService {

    @Resource
    private ReceiverAddressRepository receiverAddressRepository;

    protected Page<ReceiverAddress> pageReceiverAddress(PageVO pageVO, Long memberId, Long roleId) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());

        return receiverAddressRepository.findAll((Specification<ReceiverAddress>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            predicateList.add(cb.equal(root.get("memberId"), memberId));
            predicateList.add(cb.equal(root.get("roleId"), roleId));
            predicateList.add(cb.equal(root.get("createType"), ReceiverAddressCreateTypeEnum.LOGISTICS.getCode()));

            Predicate[] p = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(p)).getRestriction();
        }, page);
    }


    /**
     * 保存收货地址
     * @param request  接口参数
     * @param memberId 会员id
     * @param roleId   角色id
     * @return 收货地址信息
     */
    protected ReceiverAddress saveReceiverAddress(BaseReceiverAddressRequest request, Long memberId, Long roleId) {
        this.updateAllStateNotDefault(request.getIsDefault(), memberId, roleId);

        ReceiverAddress receiverAddress = new ReceiverAddress();
        receiverAddress.setReceiverName(request.getReceiverName());
        receiverAddress.setProvinceCode(request.getProvinceCode());
        receiverAddress.setProvinceName(request.getProvinceName());
        receiverAddress.setCityCode(request.getCityCode());
        receiverAddress.setCityName(request.getCityName());
        receiverAddress.setDistrictCode(request.getDistrictCode());
        receiverAddress.setDistrictName(request.getDistrictName());
        receiverAddress.setStreetCode(request.getStreetCode());
        receiverAddress.setStreetName(request.getStreetName());
        receiverAddress.setAddress(request.getAddress());
        receiverAddress.setAreaCode(request.getAreaCode());
        receiverAddress.setPostalCode(request.getPostalCode());
        receiverAddress.setPhone(request.getPhone());
        receiverAddress.setTel(request.getTel());
        receiverAddress.setIsDefault(request.getIsDefault());
        receiverAddress.setMemberId(memberId);
        receiverAddress.setRoleId(roleId);
        receiverAddress.setCreateTime(System.currentTimeMillis());
        receiverAddress.setCreateType(ReceiverAddressCreateTypeEnum.LOGISTICS.getCode());
        //新增物流地址没有门店地址信息，设为默认值
        receiverAddress.setStoreId(0L);
        receiverAddress.setStoreName("");
        receiverAddress.setIsStore(CommonBooleanEnum.NO.getCode());
        receiverAddressRepository.saveAndFlush(receiverAddress);

        return receiverAddress;
    }

    /**
     * 代客下单 - 保存收货地址
     * @param request 接口参数
     * @return 收货地址信息
     */
    protected ReceiverAddress saveReceiverAddressAgent(ReceiverAddressAgentAddRequest request) {
        this.updateAllStateNotDefault(request.getIsDefault(), request.getMemberId(), request.getRoleId());

        ReceiverAddress receiverAddress = new ReceiverAddress();
        receiverAddress.setReceiverName(request.getReceiverName());
        receiverAddress.setProvinceCode(request.getProvinceCode());
        receiverAddress.setProvinceName(request.getProvinceName());
        receiverAddress.setCityCode(request.getCityCode());
        receiverAddress.setCityName(request.getCityName());
        receiverAddress.setDistrictCode(request.getDistrictCode());
        receiverAddress.setDistrictName(request.getDistrictName());
        receiverAddress.setStreetCode(request.getStreetCode());
        receiverAddress.setStreetName(request.getStreetName());
        receiverAddress.setAddress(request.getAddress());
        receiverAddress.setAreaCode(request.getAreaCode());
        receiverAddress.setPostalCode(request.getPostalCode());
        receiverAddress.setPhone(request.getPhone());
        receiverAddress.setTel(request.getTel());
        receiverAddress.setIsDefault(request.getIsDefault());
        receiverAddress.setMemberId(request.getMemberId());
        receiverAddress.setRoleId(request.getRoleId());
        receiverAddress.setCreateTime(System.currentTimeMillis());
        receiverAddress.setCreateType(ReceiverAddressCreateTypeEnum.LOGISTICS.getCode());
        //新增物流地址没有门店地址信息，设为默认值
        receiverAddress.setStoreId(0L);
        receiverAddress.setStoreName("");
        receiverAddress.setIsStore(CommonBooleanEnum.NO.getCode());
        receiverAddressRepository.saveAndFlush(receiverAddress);

        return receiverAddress;
    }

    protected void updateReceiverAddress(ReceiverAddress receiverAddress, BaseReceiverAddressRequest request) {

        this.updateAllStateNotDefault(request.getIsDefault(), receiverAddress.getMemberId(), receiverAddress.getRoleId());

        receiverAddress.setReceiverName(request.getReceiverName());
        receiverAddress.setProvinceCode(request.getProvinceCode());
        receiverAddress.setProvinceName(request.getProvinceName());
        receiverAddress.setCityCode(request.getCityCode());
        receiverAddress.setCityName(request.getCityName());
        receiverAddress.setDistrictCode(request.getDistrictCode());
        receiverAddress.setDistrictName(request.getDistrictName());
        receiverAddress.setStreetCode(request.getStreetCode());
        receiverAddress.setStreetName(request.getStreetName());
        receiverAddress.setAddress(request.getAddress());
        receiverAddress.setPostalCode(request.getPostalCode());
        receiverAddress.setAreaCode(request.getAreaCode());
        receiverAddress.setPhone(request.getPhone());
        receiverAddress.setTel(request.getTel());
        receiverAddress.setIsDefault(request.getIsDefault());

        receiverAddressRepository.saveAndFlush(receiverAddress);
    }

    /**
     * 修改会员所有记录为非默认
     * @param isDefault 是否默认
     * @param memberId  会员id
     * @param roleId    角色id
     */
    protected void updateAllStateNotDefault(Integer isDefault, Long memberId, Long roleId) {
        if (CommonBooleanEnum.YES.getCode().equals(isDefault)) {
            List<ReceiverAddress> isDefaultList = receiverAddressRepository.findAllByIsDefaultAndMemberIdAndRoleId(CommonBooleanEnum.YES.getCode(), memberId, roleId);
            List<ReceiverAddress> updateList = isDefaultList.stream().peek(e -> e.setIsDefault(CommonBooleanEnum.NO.getCode())).collect(Collectors.toList());
            receiverAddressRepository.saveAll(updateList);
        }
    }

    protected ReceiverAddressResponse convertReceiverAddressResponse(ReceiverAddress receiverAddress) {
        ReceiverAddressResponse receiverAddressResponse = new ReceiverAddressResponse();
        receiverAddressResponse.setId(receiverAddress.getId());
        receiverAddressResponse.setReceiverName(receiverAddress.getReceiverName());
        receiverAddressResponse.setProvinceCode(receiverAddress.getProvinceCode());
        receiverAddressResponse.setProvinceName(receiverAddress.getProvinceName());
        receiverAddressResponse.setCityCode(receiverAddress.getCityCode());
        receiverAddressResponse.setCityName(receiverAddress.getCityName());
        receiverAddressResponse.setDistrictCode(receiverAddress.getDistrictCode());
        receiverAddressResponse.setDistrictName(receiverAddress.getDistrictName());
        receiverAddressResponse.setStreetCode(StrUtil.isEmpty(receiverAddress.getStreetCode()) ? "" : receiverAddress.getStreetCode());
        receiverAddressResponse.setStreetName(StrUtil.isEmpty(receiverAddress.getStreetName()) ? "" : receiverAddress.getStreetName());
        receiverAddressResponse.setAddress(receiverAddress.getAddress());
        receiverAddressResponse.setPostalCode(receiverAddress.getPostalCode());
        receiverAddressResponse.setAreaCode(receiverAddress.getAreaCode());
        receiverAddressResponse.setPhone(receiverAddress.getPhone());
        receiverAddressResponse.setTel(StrUtil.isEmpty(receiverAddress.getTel()) ? "" : receiverAddress.getTel());
        receiverAddressResponse.setIsDefault(receiverAddress.getIsDefault());

        return receiverAddressResponse;
    }

    /**
     * 判断是否属于当前会员
     * @param loginMemberId 登录会员id
     * @param loginRoleId   登录会员角色id
     * @param memberId      记录的memberId
     * @param roleId        记录的roleId
     * @return true false
     */
    protected boolean isBelongCurrentMember(Long loginMemberId, Long loginRoleId, Long memberId, Long roleId) {
        return loginMemberId.equals(memberId) && loginRoleId.equals(roleId);
    }
}